Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
La conversión a ObjectId falló por valor (tipo Objeto) en la ruta "_id" para el modelo "Usuario" en mongoDB

Estoy tratando de usar el ID de usuario de userId para buscar amigos de ese usuario en particular.

 router.get("/friends/:userId", async (req, res) => { try { const user = await User.findById({userId:req.params.userId}); const friends = await Promise.all( user.following.map((friendId) => { return User.findById(friendId); }) ); let friendList = []; friends.map((friend) => { const { _id, username, profilePicture } = friend; friendList.push({ _id, username, profilePicture }); }); res.status(200).json(friendList) console.log(friendList) } catch (err) { res.status(500).json(err); console.log(err) } });

pero me sale este error

 CastError: Cast to ObjectId failed for value "{ userId: '61543261597a97bfdf670f0b' }" (type Object) at path "_id" for model "User"

datos de amigos en mi cuando me desconecto para ver...

 [ undefined, { _id: new ObjectId("6154346027ecc696433f5b86"), username: 'Hemmyhtec', email: 'emmmmaee@gmail.com', password: '$2b$10$wVkZGu4PxlmW3geXfeBwHOxGeK6v7wyjyV7xeLzBNWQSeg5LtA.eW', profilePicture: 'logo3.jpg', coverPicture: '', followers: [ '', '61543261597a97bfdf670f0b' ], following: [ '' ], isAdmin: false, createdAt: 2021-09-29T09:39:44.199Z, updatedAt: 2021-10-02T20:25:38.569Z, __v: 0 } ]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Cuando usa findById() , debe pasar solo el valor de _id y no el objeto userId con ese valor. Cambia tu código así:

 const user = await User.findById(req.params.userId);
about 4 years ago · Juan Pablo Isaza Report

0

Reemplazar esto

 user.following.map((friendId) => { return User.findById(friendId);

})

con

 user.following.map((friendId) => { if(!friendId) return return User.findById(friendId);

})

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!